layui.config({
    base : "js/"
}).use(['form','layer','jquery','laypage'],function(){
    var form = layui.form(),
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        laypage = layui.laypage,
        $ = layui.jquery;

    //http://localhost/ci/public/static/json/usersList.json
    //http://localhost/ci/admin/user/imp_index
    //加载页面数据
    var usersData = '';
    $.get("http://localhost/ci/admin/role/imp_index", {'token':localStorage.token,'user_token':localStorage.user}, function(data){
        //console.log(JSON.parse(data));
        usersData = JSON.parse(data);
        if(window.sessionStorage.getItem("addRole")){
            var addRoles = window.sessionStorage.getItem("addRole");
            usersData = JSON.parse(addRoles).concat(usersData);
        }
        if(data == '0'){
            top.location = 'http://localhost/ci/login/login/login';//整个页面进行跳转
        }
        //执行加载数据的方法
        rolesList();
    })


    //全选
    form.on('checkbox(allChoose)', function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        child.each(function(index, item){
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //通过判断文章是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)",function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
        if(childChecked.length == child.length){
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
        }else{
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
        }
        form.render('checkbox');
    })

    function rolesList(){
        //渲染数据
        function renderDate(data,curr){
            var dataHtml = '';
            currData = usersData.concat().splice(curr*nums-nums, nums);
            if(currData.length != 0){
                for(var i=0;i<currData.length;i++){
                    dataHtml += '<tr>'
                        +  '<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
                        +  '<td>'+currData[i].role_name+'</td>'
                        +  '<td>'+currData[i].remark+'</td>'
                        +  '<td>'+currData[i].create_time+'</td>'
                        +  '<td>'
                        +    '<a class="layui-btn layui-btn-mini roles_edit" data-id="'+currData[i].role_id+'"><i class="iconfont icon-edit"></i> 编辑</a>'
                        +    '<a class="layui-btn layui-btn-danger layui-btn-mini roles_del" data-id="'+currData[i].role_id+'"><i class="layui-icon">&#xe640;</i> 删除</a>'
                        +  '</td>'
                        +  '<td>'
                        +    '<a class="layui-btn layui-btn-mini role_menu" data-id="'+currData[i].role_id+'"><i class="iconfont icon-edit"></i> 权限</a>'
                        +  '</td>'
                        +'</tr>';
                }
            }else{
                dataHtml = '<tr><td colspan="8">暂无数据</td></tr>';
            }
            return dataHtml;
        }

        //分页
        var nums = 8; //每页出现的数据量
        laypage({
            cont : "page",
            pages : Math.ceil(usersData.length/nums),
            jump : function(obj){
                $(".roles_content").html(renderDate(usersData,obj.curr));
                $('.roles_list thead input[type="checkbox"]').prop("checked",false);
                form.render();
            }
        })
    }

//--------------弹出页面------------------
    //操作
    $("body").on("click",".roles_edit",function(){  //编辑
        var _this = $(this);
        $('.ci_data').val(_this.attr('data-id'));
        var index = layui.layer.open({
            title : "修改角色",
            type : 2,
            area: ['600px', '360px'],
            maxmin: true,
            shadeClose: true, //点击遮罩关闭层
            content : "http://localhost/ci/admin/role/updateRole",
            success : function(layero, index){
                layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);
        /*layer.alert('您点击了会员编辑按钮，由于是纯静态页面，所以暂时不存在编辑内容，后期会添加，敬请谅解。。。',{icon:6, title:'文章编辑'});*/
    })

    $("body").on("click",".roles_del",function(){  //删除
        var _this = $(this);
        layer.confirm('确定删除此角色吗？',{icon:3, title:'提示信息'},function(index){
            //_this.parents("tr").remove();
            for(var i=0;i<usersData.length;i++){
                if(usersData[i].role_id == _this.attr("data-id")){
                    //usersData.splice(i,1);
                    //usersList(usersData);
                    $.ajax({
                        url : "http://localhost/ci/admin/role/imp_del",
                        type : "post",
                        data : {'role_id':usersData[i].role_id, 'token':localStorage.token,'user_token':localStorage.user},
                        dataType : "json",
                        success : function(data){
                            console.log(data);
                            setTimeout(function(){
                                top.layer.msg("角色删除成功！");
                                //重新加载页面
                                location.href='http://localhost/ci/admin/role/'
                            },1000);
                        },
                        error : function (data) {
                            console.log(data);
                            //重新加载页面
                            location.href='http://localhost/ci/admin/role/'
                        }
                    })
                }
            }
            layer.close(index);
        });
    })

    //添加会员
    $(".rolesAdd_btn").click(function(){
        var index = layui.layer.open({
            title : "添加角色",
            type : 2,
            area: ['600px', '360px'],
            maxmin: true,
            shadeClose: true, //点击遮罩关闭层
            content : "http://localhost/ci/admin/role/addRole",
            success : function(layero, index){
                layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);
    })



    //------------------------查询操作---------------
        //查询
        $(".search_btn").click(function(){
            var userArray = [];
            if($(".search_input").val() != ''){
                var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
                setTimeout(function(){
                    $.ajax({
                        url : "http://localhost/ci/admin/role/imp_index",
                        type : "get",
                        data:{'token':localStorage.token,'user_token':localStorage.user},
                        dataType : "json",
                        success : function(data){
                            if(window.sessionStorage.getItem("addRoles")){
                                var addRoles = window.sessionStorage.getItem("addRoles");
                                addRoles = JSON.parse(addRoles).concat(data);
                            }else{
                                usersData = data;
                            }
                            for(var i=0;i<usersData.length;i++){
                                var usersStr = usersData[i];
                                var selectStr = $(".search_input").val();
                                function changeStr(data){
                                    var dataStr = '';
                                    var showNum = data.split(eval("/"+selectStr+"/ig")).length - 1;
                                    if(showNum > 1){
                                        for (var j=0;j<showNum;j++) {
                                            dataStr += data.split(eval("/"+selectStr+"/ig"))[j] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>";
                                        }
                                        dataStr += data.split(eval("/"+selectStr+"/ig"))[showNum];
                                        return dataStr;
                                    }else{
                                        dataStr = data.split(eval("/"+selectStr+"/ig"))[0] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>" + data.split(eval("/"+selectStr+"/ig"))[1];
                                        return dataStr;
                                    }
                                }
                                //角色名
                                if(usersStr.role_name.indexOf(selectStr) > -1){
                                    usersStr["role_name"] = changeStr(usersStr.role_name);
                                }
                                //备注
                                if(usersStr.remark.indexOf(selectStr) > -1){
                                    usersStr["remark"] = changeStr(usersStr.remark);
                                }
                                //创建时间
                                if(usersStr.create_time.indexOf(selectStr) > -1){
                                    usersStr["create_time"] = changeStr(usersStr.create_time);
                                }
                                if(usersStr.role_name.indexOf(selectStr)>-1 || usersStr.remark.indexOf(selectStr)>-1 || usersStr.create_time.indexOf(selectStr)>-1){
                                    userArray.push(usersStr);
                                }
                            }
                            usersData = userArray;
                            rolesList(usersData);
                        }
                    })
                    layer.close(index);
                },2000);
            }else{
                layer.msg("请输入需要查询的内容");
            }
        })
})